Getting Started with ESP

您所在的位置:网站首页 esp8266 espnow连上WIFI后没办法使用 Getting Started with ESP

Getting Started with ESP

2024-07-09 18:30:01| 来源: 网络整理| 查看: 265

In this article, we’ll show you how you can use ESP-NOW to exchange data between ESP8266 NodeMCU boards programmed with Arduino IDE. ESP-NOW is a connectionless communication protocol developed by Espressif that features short packet transmission and can be used with ESP8266 and ESP32 boards.

Getting Started with ESP-NOW ESP8266 NodeMCU with Arduino IDE

We have other tutorials about ESP-NOW with the ESP8266:

ESP-NOW Two-Way Communication Between ESP8266 NodeMCU Boards ESP-NOW with ESP8266: Send Data to Multiple Boards (one-to-many) ESP-NOW with ESP8266: Receive Data from Multiple Boards (many-to-one) Arduino IDE

We’ll program the ESP8266 NodeMCU board using Arduino IDE, so before proceeding with this tutorial you should have the ESP8266 add-on installed in your Arduino IDE. Follow the next guide:

Installing ESP8266 Board in Arduino IDE (Windows, Mac OS X, Linux)

Note: we have a similar guide for the ESP32: Getting Started with ESP-NOW (ESP32 with Arduino IDE).

Introducing ESP-NOW

The following video shows an introduction to ESP-NOW. This video was recorded for the ESP32, but most concepts also apply to the ESP8266 NodeMCU board.

Stating Espressif website, ESP-NOW is a “protocol developed by Espressif, which enables multiple devices to communicate with one another without using Wi-Fi. The protocol is similar to the low-power 2.4GHz wireless connectivity (…) . The pairing between devices is needed prior to their communication. After the pairing is done, the connection is safe and peer-to-peer, with no handshake being required.”

ESP-NOW - ESP32 Logo

This means that after pairing a device with each other, the connection is persistent. In other words, if suddenly one of your boards loses power or resets, when it restarts, it will automatically connect to its peer to continue the communication.

ESP-NOW supports the following features:

Encrypted and unencrypted unicast communication; Mixed encrypted and unencrypted peer devices; Up to 250-byte payload can be carried; Sending callback function that can be set to inform the application layer of transmission success or failure.

ESP-NOW technology also has the following limitations:

Limited encrypted peers. 10 encrypted peers at the most are supported in Station mode; 6 at the most in SoftAP or SoftAP + Station mode; Multiple unencrypted peers are supported, however, their total number should be less than 20, including encrypted peers; Payload is limited to 250 bytes.

In simple words, ESP-NOW is a fast communication protocol that can be used to exchange small messages (up to 250 bytes) between ESP8266 boards.

ESP-NOW is very versatile and you can have one-way or two-way communication in different setups.

ESP-NOW One-Way Communication

For example, in one-way communication, you can have scenarios like this:

One ESP8266 board sending data to another ESP8266 board ESP8266 ESP-NOW One-way Communication

This configuration is very easy to implement and it is great to send data from one board to the other like sensor readings or ON and OFF commands to control GPIOs.

A “master” ESP8266 sending data to multiple ESP8266 “slaves”

One ESP8266 board sending the same or different commands to different ESP8266 boards. This configuration is ideal to build something like a remote control. You can have several ESP8266 boards around the house that are controlled by one main ESP8266 board.

ESP-NOW master ESP8266 sending data to multiple ESP8266 slaves One ESP8266 “slave” receiving data from multiple “masters”

This configuration is ideal if you want to collect data from several sensors nodes into one ESP8266 board. This can be configured as a web server to display data from all the other boards, for example.

ESP-NOW one ESP32 slave receiving data from multiple masters

Note: in the ESP-NOW documentation there isn’t such thing as “sender/master” and “receiver/slave”. Every board can be a sender or receiver. However, to keep things clear we’ll use the terms “sender” and “receiver” or “master” and “slave”.

ESP-NOW Two-Way Communication

With ESP-NOW, each board can be a sender and a receiver at the same time. So, you can establish a two-way communication between boards.

For example, you can have two boards communicating with each other.

ESP8266 ESP-NOW Two-way Communication

You can add more boards to this configuration and have something that looks like a network (all ESP8266 boards communicate with each other).

ESP-NOW two-way communication between multiple ESP8266 boards

In summary, ESP-NOW is ideal to build a network in which you can have several ESP8266 boards exchanging data with each other.

ESP8266: Getting Board MAC Address

To communicate via ESP-NOW, you need to know the MAC Address of the ESP8266 receiver. That’s how you know to which device you’ll send the information to.

Each ESP8266 has a unique MAC Address and that’s how we identify each board to send data to it using ESP-NOW (learn how to Get and Change the ESP8266 MAC Address).

To get your board’s MAC Address, upload the following code.

/* Rui Santos & Sara Santos - Random Nerd Tutorials Complete project details at https://RandomNerdTutorials.com/get-change-esp32-esp8266-mac-address-arduino/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #include void setup(){ Serial.begin(115200); Serial.println(); Serial.print("ESP Board MAC Address: "); Serial.println(WiFi.macAddress()); } void loop(){ }

View raw code

After uploading the code, open the Serial Monitor at a baud rate of 115200 and press the ESP8266 RESET button. The MAC address should be printed as follows:

ESP-NOW ESP32 Getting Board MAC Address

Save your board MAC address because you’ll need it to send data to the right board via ESP-NOW.

ESP-NOW One-way Point to Point Communication with ESP8266

To get you started with ESP-NOW wireless communication, we’ll build a simple project that shows how to send a message from one ESP8266 to another. One ESP8266 will act as a “sender” and the other ESP8266 will be the “receiver”.

ESP8266 ESP-NOW One-way Communication Example with Arduino IDE

We’ll send a structure that contains a variable of type char, int, float, String and boolean. Then, you can modify the structure to send whichever variable types are suitable for your project (like sensor readings, or boolean variables to turn something on or off).

For better understanding we’ll call “sender” to ESP8266 #1 and “receiver” to ESP8266 #2.

Here’s what we should include in the sender sketch:

Initialize ESP-NOW; Register a callback function upon sending data – the OnDataSent function will be executed when a message is sent. This can tell us if the message was successfully delivered or not; Add a peer device (the receiver). For this, you need to know the the receiver MAC address; Send a message to the peer device.

On the receiver side, the sketch should include:

Initialize ESP-NOW; Register for a receive callback function (OnDataRecv). This is a function that will be executed when a message is received. Inside that callback function save the message into a variable to execute any task with that information.

ESP-NOW works with callback functions that are called when a device receives a message or when a message is sent (you get if the message was successfully delivered or if it failed).

ESP-NOW Useful Functions

Here’s a summary of most essential ESP-NOW functions:

Function Name and Descriptionesp_now_init() Initializes ESP-NOW. You must initialize Wi-Fi before initializing ESP-NOW. Returns 0, if succeed.esp_now_set_self_role(role) the role can be: ESP_NOW_ROLE_IDLE = 0,ESP_NOW_ROLE_CONTROLLER, ESP_NOW_ROLE_SLAVE, ESP_NOW_ROLE_COMBO, ESP_NOW_ROLE_MAXesp_now_add_peer(uint8 mac_addr, uint8 role, uint8 channel, uint8 key, uint8 key_len) Call this function to pair a device.esp_now_send(uint8 mac_address, uint8 data, int len) Send data with ESP-NOW.esp_now_register_send_cb() Register a callback function that is triggered upon sending data. When a message is sent, a function is called – this function returns whether the delivery was successful or not.esp_now_register_recv_cb() Register a callback function that is triggered upon receiving data. When data is received via ESP-NOW, a function is called.

For more information about these functions:

ESP-NOW documentation at Read the Docs ESP8266 API reference from Espressif ESP8266 NodeMCU Sender Sketch (ESP-NOW)

Here’s the code for the ESP8266 NodeMCU Sender board. Copy the code to your Arduino IDE, but don’t upload it yet. You need to make a few modifications to make it work for you.

/* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp-now-esp8266-nodemcu-arduino-ide/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #include #include // REPLACE WITH RECEIVER MAC Address uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // Structure example to send data // Must match the receiver structure typedef struct struct_message { char a[32]; int b; float c; String d; bool e; } struct_message; // Create a struct_message called myData struct_message myData; unsigned long lastTime = 0; unsigned long timerDelay = 2000; // send readings timer // Callback when data is sent void OnDataSent(uint8_t *mac_addr, uint8_t sendStatus) { Serial.print("Last Packet Send Status: "); if (sendStatus == 0){ Serial.println("Delivery success"); } else{ Serial.println("Delivery fail"); } } void setup() { // Init Serial Monitor Serial.begin(115200); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); // Init ESP-NOW if (esp_now_init() != 0) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for Send CB to // get the status of Trasnmitted packet esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER); esp_now_register_send_cb(OnDataSent); // Register peer esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0); } void loop() { if ((millis() - lastTime) > timerDelay) { // Set values to send strcpy(myData.a, "THIS IS A CHAR"); myData.b = random(1,20); myData.c = 1.2; myData.d = "Hello"; myData.e = false; // Send message via ESP-NOW esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); lastTime = millis(); } }

View raw code

How the code works

First, include the ESP8266WiFi.h and espnow.h libraries.

#include #include

In the next line, you should insert the ESP8266 receiver MAC address.

uint8_t broadcastAddress[] = {0x5C, 0xCF, 0x7F, 0x99, 0x9A, 0xEA};

In our case, the receiver MAC address is: 5C:CF:7F:99:9A:EA, but you need to replace that variable with your own MAC address.

Then, create a structure that contains the type of data we want to send. We called this structure struct_message and it contains 5 different variable types. You can change this to send whatever variable types you want.

typedef struct struct_message { char a[32]; int b; float c; String d; bool e; } struct_message;

Create a new variable of type struct_message that is called myData that will store the variables values.

struct_message myData;

Next, define the OnDataSent() function. This is a callback function that will be executed when a message is sent. In this case, this message simply prints if the message was successfully sent or not.

void OnDataSent(uint8_t *mac_addr, uint8_t sendStatus) { Serial.print("Last Packet Send Status: "); if (sendStatus == 0){ Serial.println("Delivery success"); } else{ Serial.println("Delivery fail"); } }

In the setup(), initialize the serial monitor for debugging purposes:

Serial.begin(115200);

Set the device as a Wi-Fi station:

WiFi.mode(WIFI_STA);

Initialize ESP-NOW:

if (esp_now_init() != 0) { Serial.println("Error initializing ESP-NOW"); return; }

Set the ESP8266 role:

esp_now_set_self_role(ESP_NOW_ROLE_CONTROLLER);

It accepts the following roles: ESP_NOW_ROLE_CONTROLLER, ESP_NOW_ROLE_SLAVE, ESP_NOW_ROLE_COMBO, ESP_NOW_ROLE_MAX.

After successfully initializing ESP-NOW, register the callback function that will be called when a message is sent. In this case, we register for the OnDataSent() function created previously.

esp_now_register_send_cb(OnDataSent);

Then, pair with another ESP-NOW device to send data:

esp_now_add_peer(broadcastAddress, ESP_NOW_ROLE_SLAVE, 1, NULL, 0);

The esp_now_add_peer accepts the following arguments, in this order: mac address, role, wi-fi channel, key, and key length.

In the loop(), we’ll send a message via ESP-NOW every 2 seconds (you can change this delay time on the timerDelay variable).

First, we set the variables values as follows:

strcpy(myData.a, "THIS IS A CHAR"); myData.b = random(1,20); myData.c = 1.2; myData.d = "Hello"; myData.e = false;

Remember that myData is a structure. Here we assign the values we want to send inside the structure. For example, the first line assigns a char, the second line assigns a random Int number, a Float, a String and a Boolean variable.

We create this kind of structure to show you how to send the most common variable types. You can change the structure to send any other type of data.

Finally, send the message as follows:

esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData));

The loop() is executed every 2000 milliseconds (2 seconds).

if ((millis() - lastTime) > timerDelay) { // Set values to send strcpy(myData.a, "THIS IS A CHAR"); myData.b = random(1,20); myData.c = 1.2; myData.d = "Hello"; myData.e = false; // Send message via ESP-NOW esp_now_send(broadcastAddress, (uint8_t *) &myData, sizeof(myData)); lastTime = millis(); } ESP8266 NodeMCU Receiver Sketch (ESP-NOW)

Upload the following code to your ESP8266 NodeMCU receiver board.

/* Rui Santos Complete project details at https://RandomNerdTutorials.com/esp-now-esp8266-nodemcu-arduino-ide/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files. The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. */ #include #include // Structure example to receive data // Must match the sender structure typedef struct struct_message { char a[32]; int b; float c; String d; bool e; } struct_message; // Create a struct_message called myData struct_message myData; // Callback function that will be executed when data is received void OnDataRecv(uint8_t * mac, uint8_t *incomingData, uint8_t len) { memcpy(&myData, incomingData, sizeof(myData)); Serial.print("Bytes received: "); Serial.println(len); Serial.print("Char: "); Serial.println(myData.a); Serial.print("Int: "); Serial.println(myData.b); Serial.print("Float: "); Serial.println(myData.c); Serial.print("String: "); Serial.println(myData.d); Serial.print("Bool: "); Serial.println(myData.e); Serial.println(); } void setup() { // Initialize Serial Monitor Serial.begin(115200); // Set device as a Wi-Fi Station WiFi.mode(WIFI_STA); // Init ESP-NOW if (esp_now_init() != 0) { Serial.println("Error initializing ESP-NOW"); return; } // Once ESPNow is successfully Init, we will register for recv CB to // get recv packer info esp_now_set_self_role(ESP_NOW_ROLE_SLAVE); esp_now_register_recv_cb(OnDataRecv); } void loop() { }

View raw code

How the code works

Similarly to the sender, start by including the libraries:

#include #include

Create a structure to receive the data. This structure should be the same defined in the sender sketch.

typedef struct struct_message { char a[32]; int b; float c; String d; bool e; } struct_message;

Create a struct_message variable called myData.

struct_message myData;

Create a callback function that will be called when the ESP8266 receives the data via ESP-NOW. The function is called onDataRecv() and should accept several parameters as follows:

void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len) {

We copy the content of the incomingData data variable into the myData variable.

memcpy(&myData, incomingData, sizeof(myData));

Now, the myData structure contains several variables inside with the values sent by the sender ESP8266. To access variable a, for example, we just need to call myData.a.

In this example, we simply print the received data, but in a practical application you can print the data on a display, for example.

Serial.print("Bytes received: "); Serial.println(len); Serial.print("Char: "); Serial.println(myData.a); Serial.print("Int: "); Serial.println(myData.b); Serial.print("Float: "); Serial.println(myData.c); Serial.print("String: "); Serial.println(myData.d); Serial.print("Bool: "); Serial.println(myData.e); Serial.println(); }

In the setup(), intialize Serial communication for debugging purposes.

Serial.begin(115200);

Set the device as a Wi-Fi Station.

WiFi.mode(WIFI_STA);

Initialize ESP-NOW:

if (esp_now_init() != ESP_OK) { Serial.println("Error initializing ESP-NOW"); return; }

Set the ESP8266 role:

esp_now_set_self_role(ESP_NOW_ROLE_SLAVE);

Register for a callback function that will be called when data is received. In this case, we register for the OnDataRecv() function that was created previously.

esp_now_register_recv_cb(OnDataRecv); Testing ESP-NOW Communication

Upload the sender sketch to one board and the receiver sketch to the other board. Don’t forget to insert the receiver MAC address on the sender sketch.

Now, open two Arduino IDE windows. One for the receiver, and another for the sender. Open the Serial Monitor for each board. It should be a different COM port for each board.

This is what you should get on the sender side.

Testing ESP-NOW Communication ESP8266 with Arduino IDE Sender

And this is what you should get on the receiver side. Note that the Int variable changes between each reading received (because we set it to a random number in the sender side).

Testing ESP-NOW Communication ESP32 with Arduino IDE Receiver

We tested the communication range between the two boards, and we are able to get a stable communication up to 140 meters (approximately 459 feet) in open field. In this experiment both ESP8266 on-board antennas were pointing to each other.

ESP-NOW communication range test ESP8266 NodeMCU boards Wrapping Up

In this tutorial you’ve learned how to use ESP-NOW with the ESP8266 NodeMCU board. Now, you can combine the sender and receiver sketch so that you have a two-way communication (each board acting as a server and sender at the same time). You can also use more boards to have a communication between multiple boards.

ESP8266 and ESP32 boards can communicate with each other using ESP-NOW communication protocol. You just need to upload the proper sketches to each board. To learn how to use ESP-NOW with the ESP32, you can read our ESP-NOW getting started guide for the ESP32.

We hope you’ve found this tutorial useful. To learn more about the ESP8266 board, make sure you take a look at our resources:

Home Automation with ESP8266 MicroPython Programming with ESP32 and ESP8266 More ESP8266 resources…

Thanks for reading.



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭